import time

from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.base import RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response

from common.logs import http


class HttpLogInfoMiddleware(BaseHTTPMiddleware):
    """请求耗时 日志"""
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        start = time.time()
        response = await call_next(request)
        http(request, response, time.time() - start)
        return response


middlewares = [
    Middleware(CORSMiddleware, allow_origins=['*']),
    Middleware(HttpLogInfoMiddleware)
]


__all__ = ["middlewares"]
